package com.woniuxy.commons.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.utile.Result;
import com.woniuxy.controller.dto.AccountDto;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class RoleFilter extends OncePerRequestFilter {

    private ObjectMapper om = new ObjectMapper();

    private AntPathMatcher am = new AntPathMatcher();

    public void write(HttpServletResponse response, Result result) throws IOException {
        //设置字符编码以及响应上下文类型
        response.setContentType("application/json;charset=utf8");
        response.setCharacterEncoding("utf8");

        String json = om.writeValueAsString(result);

        response.getWriter().write(json);
        response.getWriter().flush();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //取出当前访问的资源
        String uri = request.getRequestURI();
        System.out.println(uri);

        Authentication authen = SecurityContextHolder.getContext().getAuthentication();
        if (!(authen.getPrincipal() instanceof AccountDto)){
            filterChain.doFilter(request,response);
            return;
        }
        //取出当前账号具有的资源
       AccountDto AccountDto = (AccountDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //匹配两者关系
        if (AccountDto.getRoles()==null || AccountDto.getRoles().size()<=0){
            Result result = new Result().setMessage("不能访问").setCode(401);
            write(response,result);
            return;
        }
        for (String role : AccountDto.getRoles()) {
            if (am.match(role,uri)){
                filterChain.doFilter(request,response);
                return;
            }
        }
        Result result = new Result().setMessage("不能访问").setCode(401);
        write(response,result);
    }

}
